package com.itheima.stock.service.imp;

import com.google.common.base.Strings;
import com.itheima.stock.common.domian.*;
import com.itheima.stock.config.StockInfoConfig;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.service.Stock_rtIndexInfoService;
import com.itheima.stock.utils.DateTimeUtil;
import com.itheima.stock.vo.code.ResponseCode;
import com.itheima.stock.vo.result.R;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.index.PathBasedRedisIndexDefinition;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: siwukun
 * @date: 2022/06/02
 * @description: 股票成交量对比
 */
@Service
public class Stock_rtIndexInfoServiceImpl implements Stock_rtIndexInfoService {

    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;
    @Autowired
    private StockInfoConfig stockInfoConfig;

    @Autowired
    private StockBusinessMapper stockBusinessMapper;

    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;

    /**
     * 股票成交量对比
     *
     * @return
     */
    @Override
    public R<Map<String, List>> queryAllMarketInfoUpDown() {
        //T日大盘时间
        //getLastDate4Stock 获取最近股票交易日时间
        Date startTimePoint = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        Date endTimePoint = DateTimeUtil.getOpenDate(DateTime.now()).toDate();
        //制造假数据
        startTimePoint = DateTime.parse("2022-01-03 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        endTimePoint = DateTime.parse("2022-01-03 14:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        //T-1大盘时间
        //getPreviousTradingDay 获取上一个股票交易日时间
        Date startTimePointT1 = DateTimeUtil.getPreviousTradingDay(DateTime.now()).toDate();
        Date endTimePointT1 = DateTimeUtil.getOpenDate(DateTime.now()).toDate();
        //制造T1假数据
        startTimePointT1 = DateTime.parse("2022-01-02 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        endTimePointT1 = DateTime.parse("2022-01-02 14:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        //统计T日交易量数据信息
        //1.获取国内A股大盘的id集合
        List<String> inners = stockInfoConfig.getInner();
        List<Map> volList =null;
        List<Map> yesVolList =null;
        for (String code : inners) {
            volList = stockMarketIndexInfoMapper.queryAllMarketInfoUpDown(startTimePoint, endTimePoint, code);
            yesVolList = stockMarketIndexInfoMapper.queryAllMarketInfoUpDown(startTimePointT1, endTimePointT1, code);
        }
//        List<Map> volList = stockMarketIndexInfoMapper.queryAllMarketInfoUpDown(startTimePoint, endTimePoint, inners);
//        List<Map> yesVolList = stockMarketIndexInfoMapper.queryAllMarketInfoUpDown(startTimePointT1, endTimePointT1, inners);
        if (volList == null || yesVolList == null) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        //组装数据 响应给前端
        Map<String, List> map = new HashMap<>();
        map.put("volList", volList);
        map.put("yesVolList", yesVolList);
        return R.ok(map);
    }

    /**
     * 个股分时涨跌幅度统计
     *
     * @return
     */
    @Override
    public R<Map> queryAllStockGain() {

        Date recentTimePoint = commonDateTime("2022-01-06 14:30:00");
        //获取涨幅区间
        List<String> upDownRate = stockInfoConfig.getUpDownRate();
        List<Map> stockInfos = stockMarketIndexInfoMapper.queryAllStockGainByDate(recentTimePoint);
        if (stockInfos == null) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        //数据组装到mapList中
        List<Map> mapList = upDownRate.stream().map(title -> {
            //定义一个全新的map用来接收数据
            Map maps = null;
            //findFirst 只过滤一条数据
            Optional<Map> map = stockInfos.stream().filter(data -> data.containsValue(title)).findFirst();
            //isPresent() 判断是否包含对象，如果有则返回 true，如果没有则返回 false
            if (map.isPresent()) {
                maps = map.get();
            } else {
                maps = new HashMap();
                maps.put("count", 0);
                maps.put("title", title);
            }
            return maps;
        }).collect(Collectors.toList());
        Map<String, Object> maps = new HashMap();
        maps.put("time", new DateTime(recentTimePoint).toString(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")));
        maps.put("infos", mapList);
        return R.ok(maps);
    }

    /**
     * 查询个股的分时行情数据
     *
     * @param code 股票代码
     * @return List
     */
    @Override
    public R<List<Stock4MinuteDomain>> qureyStockTimeSharing(String code) {

        //getLastDate4Stock 获取最近股票交易日时间
        List<Date> dateList = commonDateTime("2021-12-30 09:30:00", "2021-12-30 14:30:00");
        Object[] date = dateList.toArray();
        //查询个股分时行情数据
        List<Stock4MinuteDomain> list = stockMarketIndexInfoMapper.qureyStockTimeSharing(code, date[0], date[1]);
        if (list == null) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(list);
    }

    @Override
    public R<List<Stock4MinuteDomain>> queryDayKLine(String code) {
        //getLastDate4Stock 获取最近股票交易日时间
        List<Date> dateList = commonDateTime("2022-01-01 09:30:00", "2022-01-06 14:25:00");
        Object[] times = dateList.toArray();
        //查询最大时间
        List<Date> maxTimes = stockMarketIndexInfoMapper.selectMaxTime(code, times[0], times[1]);
        //查询日k线行情数据
        List<Stock4MinuteDomain> list = stockMarketIndexInfoMapper.queryDayKLine(code, maxTimes,times[0], times[1]);
        return R.ok(list);
    }

    /**
     * 查询所有的股票代码
     *
     * @return allACode
     */
    @Override
    public R<List> queryAllACode(String searchStr) {
        List<Map> allACode = stockMarketIndexInfoMapper.queryAllACode(searchStr);
        if (allACode == null) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(allACode);
    }

    /**
     * 个股主营业务查询接口
     *
     * @param code code码
     * @return List
     */
    @Override
    public R<StockBusiness> queryMainBusinessOfIndividualStocks(String code) {

        if (Strings.isNullOrEmpty(code)) {
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }

        StockBusiness mapList = stockBusinessMapper.queryMainBusinessOfIndividualStocks(code);

        if (mapList == null) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(mapList);


    }

    /**
     * 周k线
     *
     * @param code code码
     * @return
     */

    @Override
    public R<List<StockWeekLineDomain>> queryWeeKLine(String code) {
        //getLastDate4Stock 获取最近股票交易日时间
        List<Date> dateList = commonDateTime("2022-01-01 09:30:00", "2022-01-30 14:25:00");
        Object[] array = dateList.toArray();
        //根据条件查询最大时间，最小时间
        List<StockWeekDomain> datas = stockMarketIndexInfoMapper.selectAllData(code, array[0], array[1]);
        //查询周k线行情数据
        List<StockWeekLineDomain> list =new ArrayList<>();
        for (StockWeekDomain data : datas) {
            StockWeekLineDomain  stockWeekLineDomain = stockMarketIndexInfoMapper.queryWeekLine(code
                    ,data.getMxTime(),data.getMiTime());
            list.add(stockWeekLineDomain);
        }
        return R.ok(list);
    }

    /**
     * 个股最新分时行情数据
     *
     * @param code code码
     * @return
     */
    @Override
    public R<StockRtIndexInfoDomain> queryTheLatestTimeSharingQuotationOfIndividualStocks(String code) {

        if (Strings.isNullOrEmpty(code)) {
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        Date recentTimePoint = commonDateTime("2022-01-06 14:30:00");
        StockRtIndexInfoDomain stockRtIndexInfoDomain = stockMarketIndexInfoMapper.queryTheLatestTimeSharingQuotationOfIndividualStocks(code, recentTimePoint);
        if (stockRtIndexInfoDomain == null) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(stockRtIndexInfoDomain);
    }

    /**
     * 个股实时交易流水查询
     *
     * @param code
     * @return
     */
    @Override
    public R<List<StockFlowDomain>> queryGStockFlow(String code) {
        if (Strings.isNullOrEmpty(code)) {
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        List<StockFlowDomain> stockFlowDomainList = stockMarketIndexInfoMapper.queryGStockFlow(code);
        if (stockFlowDomainList == null) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(stockFlowDomainList);
    }

    /**
     * 时间
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    private List<Date> commonDateTime(String startTime, String endTime) {

        //getLastDate4Stock 获取最近股票交易日时间
        Date startTimePoint = DateTimeUtil.getOpenDate(DateTime.now()).toDate();
        Date endTimePoint = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        //制造假数据
        startTimePoint = DateTime.parse(startTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        endTimePoint = DateTime.parse(endTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<Date> listDate = new ArrayList();
        Collections.addAll(listDate, startTimePoint, endTimePoint);
        return listDate;
    }

    /**
     * 获取最近交易时间
     *
     * @param curTime 最近交易时间
     * @return
     */
    private Date commonDateTime(String curTime) {
        //getLastDate4Stock 获取最近股票交易日时间
        Date curTimePoint = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        //制造假数据
        curTimePoint = DateTime.parse(curTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        return curTimePoint;
    }
}
